var workbook;
var jsonexcel;

layui.use(['form'], function () {
    var form = layui.form,
        layer = layui.layer,
        $ = layui.$;

    //监听提交
    form.on('submit(saveBtn)', function (data) {
        submitMembers(data.field);
        return false;
    });

    window.submitMembers = function () { 
        for (let x = 0;x<jsonexcel.length;x++){ //清洗无效行数据
            if (Object.keys(jsonexcel[x]).length != Object.keys(jsonexcel[0]).length){
                jsonexcel.splice(x,1);
                continue;
            }
        }
    
        // 获取数据对照表 [{dbkey:username,impkey:收件人}]
        let mapdata=getMaplist();
        // 依照mapdata修改jsonexcel中的键，重组成resdata
        let resdata = new Array(jsonexcel.length).fill({});
    
        for (let y = 0; y < mapdata.length; y++) {//4
            let a = mapdata[y].dbkey;
            let b = mapdata[y].impkey;
            let d = jsonexcel.map(function(item){
                return{
                    [a]:item[b]
                }
            });
    
            for (let zz in d){
                if (Object.keys(d[zz]) == "userphone"){
                    // console.log("Debug A!!",x,selectPhoneNum(d[zz].userphone));
                    d[zz].userphone = selectPhoneNum(d[zz].userphone);
                }
                resdata[zz] = {...resdata[zz],...d[zz]};
            }
    
        }
        let querydata = uniqueArr(resdata);
        for (let a in querydata){
            querydata[a].mem_uid = uuid();
        }
        // console.log("Debug querydata:",querydata);
        var wait = layer.load();
        // return resdata;
        // 调用接口/Member/add，添加数据
        $.ajax({
            url:"/Member/add",
            type:"post",
            data:JSON.stringify(querydata),
            datatype:"json",
            success:(res)=>{
                layer.close(wait);
                var index = layer.alert(JSON.stringify(res), {
                    title: '最终的提交信息'
                }, function () {
    
                    // 关闭弹出层
                    layer.close(index);
    
                    var iframeIndex = parent.layer.getFrameIndex(window.name);
                    parent.layer.close(iframeIndex);
                });
            }
        })
    }
    window.getMaplist = function () {
        let res=[];

        var objselect = document.getElementsByClassName('import');  
        
        for (x = 0; x < objselect.length; x++) {
            var dbkey = objselect[x].id;
            var impkey = $("#"+ dbkey +" option:selected").val();
            if (impkey != "default") {
                let c = new Object();
                c.dbkey = dbkey;
                c.impkey = impkey;
                res.push(c);
            }
        }
        return res;
    }

    window.init = function () { 
        var selectObj = document.getElementById("sheetNames");

        // 监听member-file变更，更新sheetNames下拉列表
        document.getElementById('member-file').addEventListener('change', function(e) {   //选择文件后执行
            // 清理下拉列表（sheetNames）
            $('#sheetNames option').remove();
    
            var optEle1 = document.createElement("option");
            optEle1.setAttribute("value","default");
            optEle1.appendChild(document.createTextNode("==选择sheetname=="));
            selectObj.appendChild(optEle1);
    
            let  files = e.target.files;
            if(files.length == 0) return;
            let  file = files[0];
            let  reader = new FileReader();
            reader.readAsBinaryString(file);
            reader.onload = function(e) {   //处理load事件。读取操作完成时触发。
                let  data = e.target.result;
                
                workbook = XLSX.read(data, {type: 'binary'}); //XLSX：/xlsx.core.min.js 通过XLSX.read(data, {type: type})方法读取excel 后面介绍
    
                let  sheetNames = workbook.SheetNames; // 工作表名称集合
                for (i = 0;i<sheetNames.length;i++) {
                                
                    // 填充sheetname下拉列表
                    var optEle2 = document.createElement("option");
                    optEle2.setAttribute("value",sheetNames[i]);
                    optEle2.appendChild(document.createTextNode(sheetNames[i]));
                    selectObj.appendChild(optEle2);
                }
                layui.form.render("select");
                // let  json = XLSX.utils.sheet_to_json(worksheet); //  读取workbook  这里可以自己写方法输出表格 这里建议使用XLSX.utils.工具类输出数据   这里以json格式输出数据 还有其他格式 代码后介绍
                // if(typeof(callback) == "function") callback(json);   //回调 
                //  document.getElementById('member-file').value = null; //读取后清空
            };
        });
    
        layui.form.on('select(sheetNames)', function(data){
            // 清理表单中select的option
            $('.import option').remove();
            var mappingMembers = document.getElementById("mapping_member");
    
            const sheet2JSONOpts = {
                defval:''
            }
            
            jsonexcel =  XLSX.utils.sheet_to_json(workbook.Sheets[data.value],sheet2JSONOpts);
    
            //判断如果sheet页数据为空，则提示
            if (jsonexcel.length == 0) {
                alert("此页无数据，请选择其它sheet！");  
            }else{
                var title = [
                    {"id":"username", "view":"姓名"},
                    {"id":"userphone", "view":"手机号"},
                    {"id":"province", "view":"省"},
                    {"id":"city", "view":"市"},
                    {"id":"district", "view":"区"},
                    {"id":"detailaddress", "view":"详细地址"},
                    {"id":"fulladdress", "view":"完整地址"}
                ];
                for (var x=0 ; x< title.length ; x++){
                    var objselect = document.getElementById(title[x].id);
    
                    var optEle = document.createElement("option");
                    optEle.setAttribute("value", "default");
                    optEle.appendChild(document.createTextNode("===选择列==="));
                    objselect.appendChild(optEle);
    
                    for (var y = 0 ; y < Object.keys(jsonexcel[0]).length ; y++){   //长度由sheet页内，列的数量决定
                        var optEle1 = document.createElement("option");
                        // 需要excel标题列名称
                        optEle1.setAttribute("value",Object.keys(jsonexcel[0])[y]);
                        optEle1.appendChild(document.createTextNode(Object.keys(jsonexcel[0])[y]));
                        objselect.appendChild(optEle1);
                    }
                }
            }
            layui.form.render(null,'maprules');
        });
    }

});

function uuid(){
	return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,function (c) {
		var r =Math.random() * 16 | 0 ,
		 v = c == 'x' ? r: (r & 0x3|0x8);
		return v.toString(16);
	})
}

// function getMaplist(){  //获取数据映射规则，对照

// }

function selectPhoneNum(str) {//截取手机号
    let regx = /(1[3|4|5|7|8][\d]{9})/g;
    let phoneNums = str.match(regx);
    if (phoneNums){
        for (let i = 0; i <phoneNums.length;i++){
            str = phoneNums[i];
        }
    }
    return str
}

function uniqueArr(arr) { //数组对象去重

    let result = []; //中间数组
    let tempJson = {}; //缓存对象
    for(var i = 0; i < arr.length; i++) 
    {
        //如果在结果数组result中没有找到arr[i],则把arr[i]压入结果数组result中

        if (!tempJson[JSON.stringify(arr[i])]){
            result.push(arr[i]);
            tempJson[JSON.stringify(arr[i])]=true;
        } 
    }
    return result;
}

// function init(){
    
// }

// function submitMembers(){

// }

